package core.actor.core
{
	import core.Resource.AniPackManager;
	import core.Resource.DressPack;
	import core.Resource.DressPackManager;
	import core.actor.ActorCacheManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.utils.Dictionary;
	
	import loader.LoadProxy;
	import loader.core.LoadType;
	
	import manager.SceneManager;
	
	import map.MapInfo;

	public class ActorView extends Sprite
	{

		private var _bones:Bones;
		protected var _title:Texts
		//所有层
		protected var _boneLayer:Bitmap;
		protected var _magicFrontLayer:Sprite;
		protected var _magicBackLayer:Sprite;
		protected var _textLayer:Sprite;
		
		protected var _weaponLayer:Bitmap;
		protected var _wingLayer:Bitmap;
		protected var _mountLayer:Bitmap;
		protected var _haloLayer:Bitmap;

		private var _direction:int = 0;
		
		private var _loopAction:Boolean = false;
		
		//角色动作bmd偏移
		private var _offsetX:int = 150;
		private var _offsetY:int = 270;
		
		/**
		 * initLayer(子类调用)
		 * initTitle(子类调用)
		 * initBone
		 * doAction
		 * */
		public function ActorView()
		{
			//生成绘制层数组
			//var layers:Vector.<Bitmap> = initLayer("0,0,-1,-1,-1");
			
			this.graphics.beginFill(0xff0000);
			this.graphics.drawCircle(150,270,20);
			
			
			//initTitle("测试人物");
			
			//初始化位置
			
		}
		
		protected function initTitle(title:String,type:int = 0):void
		{
			//添加文字
			_title = new Texts(this,_offsetX*2);
			_title.text = title;
			_title.x = 0;
			_title.y = _offsetY - 150;
		}

		
		
		
		//减掉偏移量
		public override function set x(value:Number):void
		{
			super.x = value-_offsetX;
		}
		//减掉偏移量
		public override function set y(value:Number):void
		{
			super.y = value-_offsetY;
		}
		
		/**
		 * @param typeString 标明初始化的层和模板类型，传入顺序是bone,weapon,wing,mount,halo.如果不要该层则传入-1,否则传template号
		 * */
		protected function initLayer(typeString:String):void
		{
			var layers:Vector.<Bitmap> = new Vector.<Bitmap>();
			var templatesCode:Array = typeString.split(",");
			var bmdTemplate:BitmapData;
			//TODO：未添加保护，应确保传入参数长度为5；
			
			if(templatesCode[4] != "-1")
			{
				bmdTemplate = ActorCacheManager.instance.getActorTemplate(int(templatesCode[4]));
				_haloLayer = new Bitmap();
				_haloLayer.bitmapData = bmdTemplate;
				_haloLayer.name = "Halo";
				addChild(_haloLayer);
				layers.push(_haloLayer);
			}
			if(templatesCode[3] != "-1")
			{
				bmdTemplate = ActorCacheManager.instance.getActorTemplate(int(templatesCode[3]));
				_mountLayer = new Bitmap();
				_mountLayer.bitmapData = bmdTemplate;
				_mountLayer.name = "Mount";
				addChild(_mountLayer);
				layers.push(_mountLayer);
			}
			if(templatesCode[2] != "-1")
			{
				bmdTemplate = ActorCacheManager.instance.getActorTemplate(int(templatesCode[2]));
				_wingLayer = new Bitmap();
				_wingLayer.bitmapData = bmdTemplate;
				_wingLayer.name = "Wing";
				addChild(_wingLayer);
				layers.push(_wingLayer);
			}
			if(templatesCode[1] != "-1")
			{
				bmdTemplate = ActorCacheManager.instance.getActorTemplate(int(templatesCode[1]));
				_weaponLayer = new Bitmap();
				_weaponLayer.bitmapData = bmdTemplate;
				_weaponLayer.name = "Weapon";
				addChild(_weaponLayer);
				layers.push(_weaponLayer);
			}
			if(templatesCode[0] != "-1")
			{
				bmdTemplate = ActorCacheManager.instance.getActorTemplate(int(templatesCode[0]));
				_boneLayer = new Bitmap();
				_boneLayer.bitmapData = bmdTemplate;
				_boneLayer.name = "bone";
				addChild(_boneLayer);
				layers.push(_boneLayer);
				
			}
	
			//初始化完层，确定了需要哪些层，初始化小人骨骼
			_bones = new Bones(layers);//骨骼显示，动画逻辑layers;
			_bones.addEventListener(Bones.ACTION_FINISH,bonesActionFinishHandler);
		}

		private function update(e:TickEvent):void
		{
			_bones.update();
		}
		
		/**
		 * 初始化方法
		 **/
		public function initBone(packsName:Array):void//bones是骨骼资源名//使用BoneManager
		{
			//_bones.jumpFrame = true;
			
			var packs:Array = [];
			var nameString:String = "";
			for(var i:int = 0;i<packsName.length;i++)
			{
				packs.push(DressPackManager.instance.getDress(packsName[i]));
				nameString += packsName[i] + "|";
			}
			
			var bones:Vector.<DressPack> = Vector.<DressPack>(packs);
			_bones.setDress(bones,nameString);
			
			//trace(this.)
			//this.stage.addEventListener(MouseEvent.CLICK,goto);
			
			//stage.addChild(new 
	
		}
			
		
		
		/**
		 * 更换骨骼数据
		 * */

		public function doAction(actionName:String,isLoop:Boolean = false):void
		{
			_loopAction = isLoop;
			_bones.setAnimation(AniPackManager.instance.getAni(actionName));
			TickManager.instance.addEventListener(TickEvent.TICK,update);

		}
		
		
		public function set cachePolicy(type:String):void
		{
			_bones.cachePolicy = type;
		}

		public function set jumpFrame(b:Boolean):void
		{
			_bones.jumpFrame = b;
		}

		
		private function bonesActionFinishHandler(e:Event):void
		{
			if(!_loopAction)
				stop();	
		}
		
		private function stop():void
		{
			TickManager.instance.removeEventListener(TickEvent.TICK,update);
		}
		
		/**
		 * 方向如图所示
		 *           3
		 *		  2     4 
		 *     0           1
		 *        7     5
		 *           6
		 * */
		
		public function set direction(dir:int):void
		{
			//暂时不处理大于1的情况
			if(dir>1||dir<0) return;
			_direction = dir;
			if(dir == 1) 
				_bones.flip = true;
			else if(dir == 0)
				_bones.flip = false;
		}
		
		public function get direction():int
		{
			return _direction;
		}

		//重置状态，更换action前
		public function reset():void
		{
			//停止骨骼动画
			_bones.gotoFrame1();
			//停止魔法
			//停止文字动画
		}
		
		//清空内容，回收到对象池前使用
		public function clear():void
		{
			
		}
		
		public function dispose():void
		{
			
		}


		//===========================场景运动相关===========================
		//类型
		public static const CHARACTER_PLAYER:uint=1; //代表玩家 主角
		public static const CHARACTER_OTHER_PLAYER:uint=2;  //代表其他玩家
		public static const CHARACTER_NPC:uint=3; // 代表NPC
		public static const CHARACTER_MONSTER:uint=4; //代表怪物
		public static const CHARACTER_PET:uint=5; //代表宠物
		public static const CHARACTER_FIGHTER:uint=6; //代表战斗人物
		public static const CHARACTER_MEMBER:uint=7;//队员
		public static const CHARACTER_VARM:uint=8;//装备面板上内角色
		
		//public var boneLayer:Bitmap;
		public function set boneLayer(value:Bitmap):void
		{
			_boneLayer = value;
		}
		
		public function get boneLayer():Bitmap
		{
			return _boneLayer;
		}
		
		public var cid:int=-1;
		
		public var typeId:int;//角色类型
		
		public var pos:Point = new Point();// 当前绝对位置
		private var _moveEndPos:Point = new Point();// 运动结束位置
		private var _path:Array=[];// 寻路数组
		private var _pathX:int,_pathY:int;//运动中的某路点
		
		private var _finding:Boolean=true;//取出路点
		
		private var _preSpeedX:Number;
		private var _preSpeedY:Number;
		
		private var _left:Boolean, _right:Boolean, _down:Boolean, _up:Boolean;
		public function moveTo(toX:int, toY:int):void{
			//在一帧的时间里，如果人物速度不足以运动到这一点，也就是说在一帧之后x < pathX, y < pathY
			if(toX>MapInfo.width)
				toX = MapInfo.width;
			if(toY>MapInfo.height - boneLayer.height)
				toY = MapInfo.height - boneLayer.height;
			
			if (toX == pos.x && toY == pos.y) {
				_path = [];
			} else {
				// 获取寻路数组结果
				//gamePlayerPath = _mainScene.getPath(x, y, toX, toY);
				_path = [new Point(toX, toY)];
			}
			if ( _path != null ) {
				_moveEndPos.x = toX;
				_moveEndPos.y = toY;
			}
		}
		
		public function move():Boolean{
			
			pathFinding();//取出寻出路中，要运动到的一点
			setDir();// 设置方向
			moveActor();// 移动
			
			return isMoveEnd();//运动结束
		}
		
		//取出寻出路中，要运动到的一点
		public function pathFinding():void{
			if(_finding){
				if(_path != null && _path.length > 0 && _path[0] != null){
					var point:Point = _path[0] as Point;
					if(_path.length==1){//目标点
						_pathX=_moveEndPos.x;
						_pathY=_moveEndPos.y;
					}else{
						_pathX=point.x;
						_pathY=point.y;
					}
					
					// 设置轴向分速度参数
					var temp:Number = Math.sqrt(Math.pow(_pathX - pos.x, 2) + Math.pow(_pathY - pos.y, 2));
					_preSpeedX = Math.abs(_pathX - pos.x) / temp;
					_preSpeedY = Math.abs(_pathY - pos.y) / temp;
					
					_finding=false;
				}else{
				}
			}
		}
		
		//判断要运动到的方向
		public function setDir():void{
			_left = _right = _up = _down = false; 
			if (_pathX != pos.x || _pathY != pos.y){//要运动的点等于人物当前点
				if(_pathX < pos.x){
					_left = true;
				}else if(_pathX > pos.x){
					_right = true;
				}
				if(_pathY < pos.y){
					_up = true;
				}else if(_pathY > pos.y){
					_down = true;
				}
			}
		}
		
		//移动
		public function moveActor():void{
			if(_path!=null && _path.length!= 0){//运动完取下一个路点
				if(pos.x==_pathX && pos.y==_pathY){
					_path.shift();
					_finding=true;
				}
			}
			
			var curSpeed:int
			if(_left || _right){
				curSpeed = Math.ceil(MapInfo.MOVE_SPEED * _preSpeedX);
				curSpeed = (_left == true) ? -curSpeed : curSpeed;
				pos.x+=curSpeed;
				if((_left && pos.x < _pathX) || (_right && pos.x > _pathX)){//防止越界
					pos.x = _pathX;
				}
				
				// 移动显示对象横坐标
				if(CHARACTER_PLAYER == typeId){// 主角
					if(pos.x < MapInfo.view_width / 2){
						boneLayer.x = pos.x - boneLayer.width/2;
					}
					else if(pos.x > MapInfo.width - MapInfo.view_width / 2){
						boneLayer.x = pos.x - MapInfo.width + MapInfo.view_width - boneLayer.width/2;
					}
					else if(boneLayer.x != MapInfo.view_width / 2 - boneLayer.width/2){
						boneLayer.x = MapInfo.view_width / 2 - boneLayer.width/2;
					}
					else{
						SceneManager.getInstance().mainScene.dx += curSpeed;
					}
				}
				else{// 其他
					boneLayer.x = pos.x - SceneManager.getInstance().mainScene.dx - boneLayer.width/2;
				}
			}
			
			if(_up || _down){
				curSpeed = Math.ceil(MapInfo.MOVE_SPEED * _preSpeedY);
				curSpeed = (_up == true) ? -curSpeed : curSpeed;
				pos.y+=curSpeed;
				if((_up && pos.y < _pathY) || (_down && pos.y > _pathY)){//防止越界
					pos.y = _pathY;
				}
				
				// 移动显示对象横坐标
				if(CHARACTER_PLAYER == typeId){// 主角
					if(pos.y < MapInfo.view_height / 2 - boneLayer.height){
						boneLayer.y = pos.y;
					}
					else if(pos.y > MapInfo.height - MapInfo.view_height / 2 - boneLayer.height){
						boneLayer.y = pos.y - (MapInfo.height - MapInfo.view_height); 
					}
					else if(boneLayer.y != MapInfo.view_height / 2 - boneLayer.height){
						boneLayer.y = MapInfo.view_height / 2 - boneLayer.height;
					}
					else{
						SceneManager.getInstance().mainScene.dy += curSpeed;
					}
				}
				else{// 其他
					boneLayer.y = pos.y - SceneManager.getInstance().mainScene.dy;
				}
			}
		}
		
		//运动结束
		public function isMoveEnd():Boolean{
			if(_path == null || _path.length == 0){
				return true;
			}
			return false;
		}
		
		/**
		 * 人物是否移动
		 * 判断角色在上下左右4个方向上是否有移动，
		 * 只要一个方向上有移动，则判定为角色移动  
		 * @override
		 * @return 
		 */		 
		public function isMove():Boolean{
			return _left||_right||_up||_down;
		}
	}
}